<template>
  <v-md-editor v-model="value" :disabled-menus="[]" @upload-image="handleUploadImage" :height="height + 'px'" />
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { onMounted, getCurrentInstance, ref, reactive, computed, watch } from "vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  /* 编辑器的内容 */
  value: {
    type: String,
    default: "",
  },
  /* 高度 */
  height: {
    type: Number,
    default: 400,
  },
  // 上传文件大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
});
const handleUploadImage = async (event: any, insertImage: Function, files: Array<File>) => {
  // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
  files.forEach(async (file: File) => {
    if (handleBeforeUpload(file)) {
      const formData = new FormData()
      formData.append('file', file)
      const res = await request({
        url: '/common/upload',
        method: 'POST',
        data: formData,
        headers: {
          Authorization: localStorage.getItem('token')
        }
      })
      // 回显方法
      insertImage({
        url: res.url,
        // desc: '描述',
        // width: 'auto',
        // height: 'auto',
      });
    }
  })
}
// 上传前校检格式和大小
const handleBeforeUpload = (file: File) => {
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      ElMessage({
        message: `上传文件大小不能超过 ${props.fileSize} MB!`,
        type: 'error',
        duration: 2 * 1000
      })
      return false
    }
  }
  return true
}
</script>
<style>

</style>